<?php

namespace app\api\controller;

use think\Controller;
use Yansongda\Pay\Pay;

class Order extends Controller
{
    /**
     * 下单
     */
    public function order($header, $data, $user)
    {
        $check = check_array($data, array('ids',  'day', 'time_id', 'address_type', 'address_id', 'remarks','mobile'));
//        'pay_type',
//        ids:购物车id集合，逗号隔开；
//        pay_type：支付方式：1：微信；2：支付宝；3：货到付款；
//        day：收货、提货日期；
//        time_id：1：上午时间段；2：下午时间段；
//        address_type：收货类型：1：配送上门；2：我要自提；
//        address_id：地址id；
//        remarks：备注
        if ($check['code'] != 1) {
            return $check;
        }
        if ($user['u_certification'] == 2) {
            return array('code' => -5, 'msg' => '正在申请实名认证，请认证后操作', 'data' => array());
        }
        if ($user['u_certification'] != 1) {
            return array('code' => -4, 'msg' => '请先实名认证', 'data' => array());
        }
        $ids = $data['ids'];
//        $pay_type = $data['pay_type'];
        $address_type = $data['address_type'];
        $address_id = $data['address_id'];
        $remarks = $data['remarks'];
        $system = db('system')
            ->where(array('id' => 1))
            ->find();
        if ($data['day'] == date('Y-m-d')) {
            if ($system['end_h'] <= date('H')) {
                return array('code' => 2, 'msg' => '已超过今日可配送时间，请重新选择配送时间', 'data' => array());
            }
            if ($data['time_id'] != 2) {
                return array('code' => 2, 'msg' => '今日上午已不可配送，请重新选择配送时间', 'data' => array());
            }
        }
        if (strtotime($data['day']) > time() + 9 * 24 * 3600) {
            return array('code' => 2, 'msg' => '请选择正确的配送日期', 'data' => array());
        }
        if ($data['time_id'] == 1) {
            $delivery_time = $data['day'] . ' ' . $system['am_delivery_time'];
            //收货、提货时间
        } else if ($data['time_id'] == 2) {
            $delivery_time = $data['day'] . ' ' . $system['pm_delivery_time'];
            //收货、提货时间
        } else {
            return array('code' => 2, 'msg' => '请选择正确的配送时间段', 'data' => array());
        }
        if ($address_type == 1) {
            $address = db('user_address')
                ->where(array('ua_status' => 1, 'u_id' => $user['u_id'], 'ua_id' => $address_id))
                ->find();
            if (empty($address)) {
                return array('code' => 2, 'msg' => '请选择正确的收货地址', 'data' => array());
            }
            $address1 = array('name' => $address['ua_name'], 'mobile' => $address['ua_mobile'],'user_mobile'=>'', 'place' => $address['ua_province'] . $address['ua_city'] . $address['ua_area'] . $address['ua_nearby'] . $address['ua_place']);
        } else {
            $address = db('pickup_address')
                ->where(array('pa_status' => 1, 'pa_id' => $address_id))
                ->find();
            if (empty($address)) {
                return array('code' => 2, 'msg' => '请选择正确的收货地址', 'data' => array());
            }
			if(!isset($data['mobile']) || !check_format($data['mobile'], config('regular_str.mobile'))){
				return array('code' => 2, 'msg' => '请输入正确的联系电话', 'data' => array());
			}
            $address1 = array('name' => $address['pa_name'], 'mobile' => $address['pa_mobile'],'user_mobile'=>$data['mobile'], 'place' => $address['pa_address']);
        }
        $car = db("goods_cart a")
            ->field("a.*,b.g_name,b.g_status,c.gn_price,c.gn_stock,c.gn_status,c.gn_name,c.gn_weight,c.gn_one_number,c.gn_details_number,c.gn_details_unit")
            ->join("fr_goods b", "a.g_id = b.g_id", "left")
            ->join("fr_goods_norm c", "a.gn_id = c.gn_id", "left")
            ->where(array("a.gc_id" => array('in', $ids), 'u_id' => $user['u_id']))
            ->select();
        if (empty($car)) {
            return array('code' => 2, 'msg' => '请选择购物车商品', 'data' => array());
        }
        $all_price = 0;
        $all_number=0;
        foreach ($car as $v) {
            if ($v['gc_status'] != 1) {
                return array('code' => 2, 'msg' => '购物车错误', 'data' => array());
            }
            if ($v['g_status'] != 1) {
                return array('code' => 2, 'msg' => $v['g_name'] . '-暂时停售', 'data' => array());
            }
            if ($v['gn_status'] != 1) {
                return array('code' => 2, 'msg' => $v['g_name'] . '-有规格暂时停售', 'data' => array());
            }
            if ($v['g_number'] <= 0) {
                return array('code' => 2, 'msg' => '购买商品数量必须大于1', 'data' => array());
            }
            if ($v['g_number'] > $v['gn_stock']) {
                return array('code' => 2, 'msg' => $v['g_name'] . '-库存不足', 'data' => array());
            }
            $all_price += $v['g_number'] * $v['gn_price'];
            $all_number+=$v['g_number'];
        }
        if (!empty($data['uc_id'])) {
            //优惠券id
            $uc_id = $data['uc_id'];
            $coupon = db('user_coupon a')
                ->where(array('uc_status' => 1, "uc_end_time" => array('gt', time()), 'uc_start_time' => array('elt', time()), 'u_id' => $user['u_id'], 'uc_id' => $uc_id))
                ->find();
            if (empty($coupon)) {
                return array('code' => 2, 'msg' => '请选择正确的优惠券', 'data' => array());
            }
            if ($all_price < $coupon['uc_min_buy']) {
                return array('code' => 2, 'msg' => '该优惠券不可使用', 'data' => array());
            }
        } else {
            $uc_id = 0;
            $coupon = array('uc_discount' => 0);
        }
        if ($system['exempt_freight_price'] > 0 && $all_price >= $system['exempt_freight_price']) {
            $freight = 0;
            $freight_remark = '订单满 ' . $system['exempt_freight_price'] . ' 元，免运费';
        } else {
            $freight = $system['freight'];
            $freight_remark = '订单未满 ' . $system['exempt_freight_price'] . ' 元，运费' . $freight . '元';
        }
        if($address_type == 2){
            $freight = 0;
            $freight_remark = '自提订单无配送费';
        }
        if ($system['one_buy'] > 0) {
            $integral = ($all_price / $system['one_buy']) * $system['one_integral'];
        } else {
            $integral = 0;
        }
        $real_price = $all_price + $freight - $coupon['uc_discount'];
        $order_num = date('YmdHis') . rand(1000, 9999) . '_' . $user['u_id'];
        $data1 = array('o_order_num' => $order_num, 'u_id' => $user['u_id'], 'o_all_price' => $all_price, 'uc_id' => $uc_id, 'uc_discount' => $coupon['uc_discount'], 'o_freight' => $freight, 'o_status' => 0, 'o_type' => $address_type, 'o_pay_type' => 0, 'o_pay_status' => 0, 'o_freight_remark' => $freight_remark, 'o_remarks' => $remarks, 'o_delivery_time' => $delivery_time, 'ua_id' => $address_id, 'o_address' => $address1['place'], 'o_user_name' => $address1['name'], 'o_user_mobile' => $address1['mobile'],'user_mobile'=>$address1['user_mobile'], 'o_create_time' => time(), 'o_add_integral' => $integral, 'o_real_price' => $real_price);
        if($all_number>=$system['examine_goods_num'] || $all_price>=$system['examine_order_price']){
            $data1['o_examine']=2;
        }else{
            $data1['o_examine']=0;
            $data1['o_examine_remark']='满足要求无需审核';
        }
        db()->startTrans();
        $res1 = db("order")
            ->insertGetId($data1);
        foreach ($car as $v) {
            $res2 = db('goods_norm a')
                ->where(array('gn_id' => $v['gn_id']))
                ->setInc("gn_sales", $v['g_number']);
            //增加规格销量
            $res3 = db('goods_norm a')
                ->where(array('gn_id' => $v['gn_id']))
                ->setDec("gn_stock", $v['g_number']);
            //减少规格库存
            $res4 = db('goods a')
                ->where(array('g_id' => $v['g_id']))
                ->setInc("g_sales", $v['g_number']);
            //增加商品销量
            $data2 = array('o_id' => $res1, 'u_id' => $user['u_id'], 'g_id' => $v['g_id'], 'gn_id' => $v['gn_id'], 'g_number' => $v['g_number'], 'og_create_time' => time(), 'og_all_price' => $v['g_number'] * $v['gn_price'], 'g_name' => $v['g_name'], 'gn_price' => $v['gn_price'], 'gn_name' => $v['gn_name'], 'gn_weight' => $v['gn_weight'], 'gn_one_number' => $v['gn_one_number'],'gn_details_number'=>$v['gn_details_number'],'gn_details_unit'=>$v['gn_details_unit']);
            $res5 = db("order_goods")
                ->insertGetId($data2);
            //添加订单商品数据
            $rush_goods = db('rush_goods a')
                ->field("a.*")
                ->join("fr_rush b", "a.r_id=b.r_id", "left")
                ->where("a.g_id = " . $v['g_id'] . " and a.rg_status=1 and a.rg_sales < a.rg_all and b.r_date = '" . date('Y-m-d') . "' and b.r_start_time <= " . time() . " and b.r_end_time > " . time() . " and b.r_status = 1")
                ->find();
            //限时抢购商品
            if (!empty($rush_goods)) {
                if ($rush_goods['rg_sales'] + $v['g_number'] < $rush_goods['rg_all']) {
                    //还有抢购量，加上之后也还有
                    db('rush_goods a')
                        ->where(array('rg_id' => $rush_goods['rg_id']))
                        ->setInc("rg_sales", $v['g_number']);
                    //增加已抢购量
                } else {
                    //还有抢购量，但加上之后则没有了
                    $all = $rush_goods['rg_sales'] + $v['g_number'];
                    db('rush_goods a')
                        ->where(array('rg_id' => $rush_goods['rg_id']))
                        ->update(array('rg_sales' => $all, 'is_full' => 1));
                    //全部抢购完
                }

            }
            if ($res2 == false || $res3 == false || $res4 == false || $res5 <= 0) {
                break;
            }
        }
        if ($uc_id > 0) {
            $res6 = db('user_coupon a')
                ->where(array('uc_status' => 1, "uc_end_time" => array('gt', time()), 'uc_start_time' => array('elt', time()), 'u_id' => $user['u_id'], 'uc_id' => $uc_id))
                ->update(array('o_id' => $res1, 'uc_use_time' => time(), 'uc_status' => 2));
            //消耗优惠券
            db('user_coupon_log')->insertGetId(array('ucl_create_time' => time(), 'uc_id' => $uc_id, 'u_id' => $user['u_id'], 'c_id' => $coupon['c_id'], 'c_num' => 1, 'c_type' => 4, 'o_id' => $res1, 'o_order_num' => $order_num));
            //增加优惠券记录
        } else {
            $res6 = 1;
        }
        if ($res1 > 0 && $res2 != false && $res3 != false && $res4 != false && $res5 > 0 && $res6 > 0) {
            db()->commit();
            //以下为处理支付方式
//            if ($pay_type == 1) {
//                $data0 = array('pay_type' => '微信');
//                //支付信息
//            } else if ($pay_type == 2) {
//                $data0 = array('pay_type' => '支付宝');
//                //支付信息
//            } else if ($pay_type == 3) {
//                db("order")
//                    ->where(array("o_id" => $res1))
//                    ->update(array("o_status" => 1));
//                //货到付款不需要支付信息
//                $data0 = array('pay_type' => '货到付款');
//                //支付信息
//            }
            db("goods_cart a")
                ->where(array("a.gc_id" => array('in', $ids), 'u_id' => $user['u_id']))
                ->update(array('gc_status' => 3));
            //将购物车改为申请购买
            db('order_log')->insert(array('o_id'=>$res1,'type'=>1,'uid'=>$user['u_id'],'user_name'=>$user['u_real_name'],'create_time'=>time(),'action'=>'创建订单'));
            return array('code' => 1, 'msg' => '购买成功', 'data' => array('o_id'=>$res1));
        } else {
            db()->rollback();
            return array('code' => 2, 'msg' => '购买失败', 'data' => array());
        }

    }
    /**
     * 订单列表
     */
    public function order_count($header, $data, $user)
    {
        $where = "u_id = " . $user['u_id'];
        $order = db('order')
            ->field("count(o_id) as count,o_status")
            ->where($where)
            ->order("o_status desc")
            ->group("o_status")
            ->select();
        $order1=array(
            array('status'=>-1,'num'=>0),
            array('status'=>1,'num'=>0),
            array('status'=>2,'num'=>0),
            array('status'=>3,'num'=>0),
            array('status'=>4,'num'=>0),
            array('status'=>5,'num'=>0),
        );
        foreach($order as $v){
            if ($v['o_status'] == 0) {
//                $order[$k]['status'] = 1;
                $order1[1]['num']=$v['count'];
                //未支付
            } else if ($v['o_status'] == 1) {
//                $order[$k]['status'] = 2;
                $order1[2]['num']=$v['count'];
                //待收货
            } else if ($v['o_status'] == 9) {
//                $order[$k]['status'] = 4;
                $order1[4]['num']=$v['count'];
                //售后
            } else if ($v['o_status'] == 10) {
//                $order[$k]['status'] = 3;
                $order1[3]['num']+=$v['count'];
                //已完成
            }else if ($v['o_status'] == 11) {
//                $order[$k]['status'] = 5;
                $order1[5]['num']=$v['count'];
                $order1[3]['num']+=$v['count'];
                //售后完成
            }else if ($v['o_status'] == -1) {
//                $order[$k]['status'] = -1;
                $order1[0]['num']=$v['count'];
                //已取消
            }
        }
        return array('code' => 1, 'msg' => '订单数量', 'data' => $order1);

    }

    /**
     * 订单列表
     */
    public function order_list($header, $data, $user)
    {
        $check = check_array($data, array('page', 'size', 'type'));
//        type:订单类型：0：全部；1：待付款；2：待收获；3：已完成；4：售后
        if ($check['code'] != 1) {
            return $check;
        }
        //以上是检测数据
        if (empty($data['page']) || $data['page'] <= 1) {
            $data['page'] = 1;
        }
        if (empty($data['size']) || $data['size'] < 1) {
            $data['size'] = 10;
        }
        $page = $data['page'];
        $size = $data['size'];
        $type = $data['type'];
        $now = ($page - 1) * $size;
        $where = array('u_id' => $user['u_id']);
        if ($type == 0) {
            $where = "u_id = " . $user['u_id'];
            $time = time() - 20 * 60;
//            $where .= " and ((o_status = 0 and o_create_time > $time ) or (o_status >= 1))";
            //支付之后和未支付（可支付）
        } else if ($type == 1) {
            $where['o_status'] = 0;
            $where['o_create_time'] = array('gt', time() - 20 * 60);
        } else if ($type == 2) {
            $where['o_status'] = 1;
        } else if ($type == 3) {
            $where['o_status'] = array('in', '10,11');
        } else if ($type == 4) {
            $where['o_status'] = 9;
        }else if ($type == -1) {
            $where['o_status'] = -1;
        }
        $order = db('order')
            ->field("o_id,o_order_num as order_num,o_status,o_real_price as all_price,o_pay_type as pay_type,o_pay_status as pay_status")
            ->where($where)
            ->limit("$now,$size")
            ->order("o_id desc")
            ->select();
        if (empty($order)) {
            //没有订单
            return array('code' => 1, 'msg' => '订单列表', 'data' => array('data' => array(),'max_page'=>0));
        }
        $ids = '0';
        foreach ($order as $v) {
            $ids .= ',' . $v['o_id'];
        }
        $goods = db('order_goods a')
            ->field("a.*,b.g_img")
            ->join("fr_goods b", "a.g_id = b.g_id", "left")
            ->where(array('a.o_id' => array('in', $ids)))
            ->select();
        foreach ($order as $k => $v) {
            $all_price = 0;
            foreach ($goods as $kk => $vv) {
                if ($vv['o_id'] == $v['o_id']) {
                    /*单商品多规格*/
//                    if (empty($order[$k]['goods1'][$vv['g_id']])) {
//                        $order[$k]['goods1'][$vv['g_id']] = array('g_id' => $vv['g_id'], 'name' => $vv['g_name'], 'img_url' => $vv['g_img']);
//                    }
//                    $order[$k]['goods1'][$vv['g_id']]['norm'][] = array(//
//                        'gn_id' => $vv['gn_id'],//规格id
//                        'name' => $vv['gn_name'],//规格名称
//                        'weight' => $vv['gn_weight'],//总重量
//                        'describe' => $vv['gn_one_number'],//总重量
//                        'price' => $vv['gn_price'],//售价
//                        'number' => $vv['g_number'],//购买量
//                        'all_price' => $vv['og_all_price'],//总价
//                    );
                    /*单商品多规格*/
                    $order[$k]['goods'][] = array(
                        'g_id' => $vv['g_id'],//商品id
                        'name' => $vv['g_name'],//商品名称
                        'img_url' => $vv['g_img'],//商品图片
                        'norm'=>array(
                            'gn_id' => $vv['gn_id'],//规格id
                            'name' => $vv['gn_name'],//规格名称
                            'weight' => $vv['gn_weight'],//总重量
                            'describe' => $vv['gn_one_number'],//总重量
                            'price' => $vv['gn_price'],//售价
                            'number' => $vv['g_number'],//购买量
                            'all_price' => $vv['og_all_price'],//总价
                            'weight_price' => round($vv['gn_price'] / ($vv['gn_weight'] * 2), 2),//单位重量价格
                            'detail_price' => round($vv['gn_price'] / ($vv['gn_details_number']), 2).'/'.$vv['gn_details_unit'],//详细价格
                        ),
                    );
                    $all_price += $vv['og_all_price'];
                }
            }
            if ($v['o_status'] == 0) {
                $order[$k]['status'] = 1;
                //未支付
            } else if ($v['o_status'] == 1) {
                $order[$k]['status'] = 2;
                //待收货
            } else if ($v['o_status'] == 9) {
                $order[$k]['status'] = 4;
                //售后
            } else if ($v['o_status'] == 10) {
                $order[$k]['status'] = 3;
                //已完成
            }else if ($v['o_status'] == 11) {
                $order[$k]['status'] = 5;
                //售后完成
            }else if ($v['o_status'] == -1) {
                $order[$k]['status'] = -1;
                //已取消
            }
//            $order[$k]['all_price']=$all_price;
        }
//        foreach ($order as $k => $v) {
//            foreach ($v['goods1'] as $vv) {
//                $order[$k]['goods'][]= $vv;
//            }
//            unset($order[$k]['goods1']);
//        }
        $count = db('order')
            ->where($where)
            ->count();
        $max_page=ceil($count/$size);
        return array('code' => 1, 'msg' => '订单列表', 'data' => array('data' => $order,'max_page'=>$max_page));
    }

    /**
     * 订单详情
     */
    public function order_details($header, $data, $user)
    {
        $check = check_array($data, array('o_id'));
//        o_id:订单id；
        if ($check['code'] != 1) {
            return $check;
        }
        $order = db('order')
            ->where(array('u_id' => $user['u_id'], 'o_id' => $data['o_id']))
            ->find();
        if (empty($order)) {
            return array('code' => 2, 'msg' => '订单出错', 'data' => array());
        }
        if ($order['o_status'] == 0) {
            $status = 1;
            //未支付
        } else if ($order['o_status'] == 1) {
            $status = 2;
            //待收货
        } else if ($order['o_status'] == 9) {
            $status = 4;
            //售后
        } else if ($order['o_status'] == 10) {
            $status = 3;
            //已完成
        }else if ($order['o_status'] == 11) {
            $status = 5;
            //售后完成
        }else if ($order['o_status'] == -1) {
            $status = -1;
            //已取消
        }
        $system=db('system')->find();
        $order1 = array(
            'o_id' => $order['o_id'],//订单id
            'order_num' => $order['o_order_num'],//订单id
            'status' => $status,//状态
            'all_price' => $order['o_all_price'],//商品总价
            'freight' => $order['o_freight'],//运费
            'discount' => $order['uc_discount'],//优惠券金额
            'real_price' => $order['o_real_price'],//实际支付价格
            'user_name' => $order['o_user_name'],//收货人名称
            'mobile' => $order['o_user_mobile'],//收货人电话
            'user_mobile' => $order['user_mobile'],//收货人电话
            'type' => $order['o_type'],//收货方式：1：配送；2：自提；
            'address' => $order['o_address'],//收货地址
            'pay_type' => $order['o_pay_type'],//支付方式
            'pay_status' => $order['o_pay_status'],//支付状态
            'remarks' => $order['o_remarks'],//备注
            'create_time' => date('Y-m-d H:i:s', $order['o_create_time']),//订单创建时间
            'delivery_time' => $order['o_delivery_time'],//收货时间
            'end_time' => $order['o_end_time'] > 0 ? date('Y-m-d H:i', $order['o_end_time']) : '',//订单结束时间
            'last_pay_time'=>date('Y-m-d H:i:s',$order['o_create_time']+20*60),
            'last_pay_time_num'=>$order['o_create_time']+20*60-time(),
            'last_collect_time'=>date('Y-m-d H:i:s',($order['o_create_time']+$system['max_days']*24*3600)),
            'is_admin'=>$order['o_is_admin_handle'],//是否后台人员操作
            'admin_remark'=>$order['o_handle_remark'],//后台人员操作的备注
        );
        $goods = db("order_goods a")
            ->field("a.*,b.g_img")
            ->join("fr_goods b", "a.g_id = b.g_id", "left")
            ->where(array("a.o_id" => $order['o_id']))
            ->select();
        if ($order['o_status'] == 0) {
            $last_time = $order['o_create_time'] + 20 * 60 - time();
            $last_time_str = floor($last_time / 60) . ':' . ($last_time % 60);
        } else {
            $last_time = 0;
            $last_time_str = '00:00';
        }
        $order1['last_time'] = $last_time;
        //剩余时间（秒）
        $order1['last_time_str'] = $last_time_str;
        //剩余时间（字符串）
        if ($status == 5 || $status == 4) {
            $return = db('order_return')
                ->where(array("o_id" => $order['o_id']))
                ->order("or_id desc")
                ->find();
        }
        if (!empty($return)) {
            $reason = $return['or_reason'];
            $reply = $return['or_reply'];
            if ($status == 4) {
                $order1['end_time']=date('Y-m-d H:i:s',$return['or_create_time']);
            }
            if ($status == 5) {
                $order1['end_time']=date('Y-m-d H:i:s',$return['order_end_time']);
            }
        } else {
            $reason = '';
            $reply = '';

        }
        $order1['reason'] = $reason;
        //退货原因
        $order1['reply'] = $reply;
        //商家反馈
        $order['goods'] = array();
        foreach ($goods as $vv) {
            $order1['goods'][] = array(
                'g_id' => $vv['g_id'],//商铺id
                'name' => $vv['g_name'],//商铺名称
                'img_url' => $vv['g_img'],//图片地址
                'gn_id' => $vv['gn_id'],//规格id
                'gn_name' => $vv['gn_name'],//规格名称
                'weight' => $vv['gn_weight'],//总重量
                'describe' => $vv['gn_one_number'],//总重量
                'price' => $vv['gn_price'],//售价
                'number' => $vv['g_number'],//购买量
                'all_price' => $vv['og_all_price'],//总价;
                'weight_price' => round($vv['gn_price'] / ($vv['gn_weight'] * 2), 2),//单位重量价格
                'detail_price' => round($vv['gn_price'] / ($vv['gn_details_number']), 2).'/'.$vv['gn_details_unit'],//详细价格
            );
        }
        return array('code' => 1, 'msg' => '订单详情', 'data' => $order1);
    }

    /**
     * 取消订单
     */
    public function order_cancel($header, $data, $user)
    {
        $check = check_array($data, array('o_id'));
//        o_id:订单id；
        if ($check['code'] != 1) {
            return $check;
        }
        $order = db('order')
            ->where(array('u_id' => $user['u_id'], 'o_id' => $data['o_id']))
            ->find();
        if (empty($order)) {
            return array('code' => 2, 'msg' => '订单出错', 'data' => array());
        }
        if ($order['o_status'] != 0 || $order['o_pay_status'] == 1) {
            return array('code' => 2, 'msg' => '该订单不可取消', 'data' => array());
        }
        db()->startTrans();
        $res1 = db("order")
            ->where(array('u_id' => $user['u_id'], 'o_id' => $data['o_id']))
            ->update(array('o_status' => -1,'o_end_time'=>time()));
        $goods = db("order_goods")
            ->where(array("o_id" => $order['o_id']))
            ->select();
        foreach ($goods as $v) {
            $res2 = db('goods_norm a')
                ->where(array('gn_id' => $v['gn_id']))
                ->setDec("gn_sales", $v['g_number']);
            //减少规格销量
            $res3 = db('goods_norm a')
                ->where(array('gn_id' => $v['gn_id']))
                ->setInc("gn_stock", $v['g_number']);
            //增加规格库存
            $res4 = db('goods a')
                ->where(array('g_id' => $v['g_id']))
                ->setDec("g_sales", $v['g_number']);
            //减少商品销量
            $res5 = 1;
            //对应添加订单商品
            $rush_goods = db('rush_goods a')
                ->field("a.*")
                ->join("fr_rush b", "a.r_id=b.r_id", "left")
                ->where("a.g_id = " . $v['g_id'] . " and a.rg_status=1 and a.rg_sales < a.rg_all and b.r_date = '" . date('Y-m-d') . "' and b.r_start_time <= " . time() . " and b.r_end_time > " . time() . " and b.r_status = 1")
                ->find();
            //限时抢购商品
            if (!empty($rush_goods)) {
                if ($rush_goods['rg_sales'] - $v['g_number'] < $rush_goods['rg_all']) {
                    //还可以继续抢购
                    $all = $rush_goods['rg_sales'] - $v['g_number'];
                    db('rush_goods a')
                        ->where(array('rg_id' => $rush_goods['rg_id']))
                        ->update(array('rg_sales' => $all, 'is_full' => 0));
                    //减少已抢购量
                } else {
                    //已抢购满了
                    $all = $rush_goods['rg_sales'] - $v['g_number'];
                    db('rush_goods a')
                        ->where(array('rg_id' => $rush_goods['rg_id']))
                        ->update(array('rg_sales' => $all, 'is_full' => 1));
                    //全部抢购完
                }

            }
            if ($res2 == false || $res3 == false || $res4 == false || $res5 <= 0) {
                break;
            }
        }
        if ($order['uc_id'] > 0) {
            $res6 = db('user_coupon a')
                ->where(array('u_id' => $user['u_id'], 'uc_id' => $order['uc_id']))
                ->update(array('o_id' => 0, 'uc_status' => 1));
            //消耗优惠券
            db('user_coupon_log')->insertGetId(array('ucl_create_time' => time(), 'uc_id' => $order['uc_id'], 'u_id' => $user['u_id'], 'c_num' => 1, 'c_type' => 5, 'o_id' => $res1, 'o_order_num' => $order['o_order_num']));
            //增加优惠券记录
        } else {
            $res6 = 1;
        }
        if ($res1 > 0 && $res2 != false && $res3 != false && $res4 != false && $res5 > 0 && $res6 > 0) {
            db('order_log')->insert(array('o_id'=>$data['o_id'],'type'=>1,'uid'=>$user['u_id'],'user_name'=>$user['u_real_name'],'create_time'=>time(),'action'=>'取消订单'));
            db()->commit();
            return array('code' => 1, 'msg' => '取消成功', 'data' => array());
        } else {
            db()->rollback();
            return array('code' => 2, 'msg' => '取消失败', 'data' => array());
        }
    }

    /**
     * 测试自动
     */
    function check_automatic()
    {
//        db('order_time_cancel')->insertGetId(array('o_id'=>0,'time'=>date('Y-m-d H:i:s'),'return'=>'定时运行'));
        $order=db('order')
            ->where(array('o_status'=>0,'o_pay_status'=>array('neq',1),'o_create_time'=>array('lt',time()-20*60)))
            ->select();
        if(!empty($order) && count($order)>0){
            $ids='0';
            foreach($order as $v){
                $ids.=','.$v['o_id'];
            }
            db("order")
                ->where(array('o_id' => array('in',$ids)))
                ->update(array('o_status' => -1,'o_end_time'=>time()));
            foreach($order as $v){
                $return=$this->automatic_order_cancel($v);
//                dump($return);
                if($return['code']!=1){
                    db("order")
                        ->where(array('o_id' => $v['o_id']))
                        ->update(array('o_status' => 0));
                }
                $return['msg']=urlencode($return['msg']);
                db('order_log')->insert(array('o_id'=>$v['o_id'],'type'=>3,'uid'=>0,'user_name'=>'','create_time'=>time(),'action'=>'自动取消订单'));
                db('order_time_cancel')->insertGetId(array('o_id'=>$v['o_id'],'time'=>date('Y-m-d H:i:s'),'return'=>urldecode(json_encode($return))));
            }
        }
        $system=db('system')->find();
        $order1=db('order')
            ->where(array('o_status'=>1,'o_pay_status'=>1,'o_create_time'=>array('lt',time()-$system['max_days']*24*3600)))
            ->select();
        if(!empty($order1) && count($order1)>0){
            foreach($order1 as $v){
                db()->startTrans();
                $res=db('order')
                    ->where(array('o_id' => $v['o_id']))
                    ->update(array('o_end_time'=>time(),'o_status'=>10,'collect'=>2));
                $user=db('user')->where(array('u_id'=>$v['u_id']))->find();
                $this->give_integral($v,$user);
                if ($res != false) {
                    db()->commit();

                    $return=array('code' => 1, 'msg' => '自动收货成功', 'data' => array());
                    $return['msg']=urlencode($return['msg']);
                    db('order_time_cancel')->insertGetId(array('o_id'=>$v['o_id'],'time'=>date('Y-m-d H:i:s'),'return'=>urldecode(json_encode($return))));
                    db('order_log')->insert(array('o_id'=>$v['o_id'],'type'=>3,'uid'=>0,'user_name'=>'','create_time'=>time(),'action'=>'自动收货'));
                } else {
                    db()->rollback();
                    $return=array('code' => 2, 'msg' => '自动收货失败', 'data' => array());
                    $return['msg']=urlencode($return['msg']);
                    db('order_time_cancel')->insertGetId(array('o_id'=>$v['o_id'],'time'=>date('Y-m-d H:i:s'),'return'=>urldecode(json_encode($return))));
                }
            }

        }
//        return json($this->automatic_order_cancel(7));
    }

    /**
     * 自动取消订单
     */
    public function automatic_order_cancel($order)
    {
        $o_id=$order['o_id'];
        if (empty($order)) {
            return array('code' => 2, 'msg' => '订单出错', 'data' => array());
        }
        if ($order['o_status'] != 0 || $order['o_pay_status'] == 1) {
            return array('code' => 2, 'msg' => '该订单不可取消'.$order['o_status'].$order['o_pay_status'], 'data' => array());
        }
        db()->startTrans();
        $res1 = 1;
        $goods = db("order_goods")
            ->where(array("o_id" => $order['o_id']))
            ->select();
        foreach ($goods as $v) {
            $res2 = db('goods_norm a')
                ->where(array('gn_id' => $v['gn_id']))
                ->setDec("gn_sales", $v['g_number']);
            //减少规格销量
            $res3 = db('goods_norm a')
                ->where(array('gn_id' => $v['gn_id']))
                ->setInc("gn_stock", $v['g_number']);
            //增加规格库存
            $res4 = db('goods a')
                ->where(array('g_id' => $v['g_id']))
                ->setDec("g_sales", $v['g_number']);
            //减少商品销量
            $res5 = 1;
            //对应添加订单商品
            $rush_goods = db('rush_goods a')
                ->field("a.*")
                ->join("fr_rush b", "a.r_id=b.r_id", "left")
                ->where("a.g_id = " . $v['g_id'] . " and a.rg_status=1 and a.rg_sales < a.rg_all and b.r_date = '" . date('Y-m-d') . "' and b.r_start_time <= " . time() . " and b.r_end_time > " . time() . " and b.r_status = 1")
                ->find();
            //限时抢购商品
            if (!empty($rush_goods)) {
                if ($rush_goods['rg_sales'] - $v['g_number'] < $rush_goods['rg_all']) {
                    //还可以继续抢购
                    $all = $rush_goods['rg_sales'] - $v['g_number'];
                    db('rush_goods a')
                        ->where(array('rg_id' => $rush_goods['rg_id']))
                        ->update(array('rg_sales' => $all, 'is_full' => 0));
                    //减少已抢购量
                } else {
                    //已抢购满了
                    $all = $rush_goods['rg_sales'] - $v['g_number'];
                    db('rush_goods a')
                        ->where(array('rg_id' => $rush_goods['rg_id']))
                        ->update(array('rg_sales' => $all, 'is_full' => 1));
                    //全部抢购完
                }

            }
            if ($res2 == false || $res3 == false || $res4 == false || $res5 <= 0) {
                break;
            }
        }
        if ($order['uc_id'] > 0) {
            $res6 = db('user_coupon a')
                ->where(array('uc_id' => $order['uc_id']))
                ->update(array('o_id' => 0, 'uc_status' => 1,'back_time'=>time()));
            //消耗优惠券
            db('user_coupon_log')->insertGetId(array('ucl_create_time' => time(), 'uc_id' => $order['uc_id'], 'u_id' => $order['u_id'], 'c_num' => 1, 'c_type' => 5, 'o_id' => $res1, 'o_order_num' => $order['o_order_num']));
            //增加优惠券记录
        } else {
            $res6 = 1;
        }
        if ($res1 > 0 && $res2 != false && $res3 != false && $res4 != false && $res5 > 0 && $res6 !== false) {
            db()->commit();
            return array('code' => 1, 'msg' => '取消成功', 'data' => array());
        } else {
            db()->rollback();
            return array('code' => 2, 'msg' => '取消失败', 'data' => array());
        }
    }
    /**
     * 订单支付
     */
    public function order_time($header, $data, $user)
    {
        $check = check_array($data, array('o_id'));
        $order = db('order')
            ->where(array('u_id' => $user['u_id'], 'o_id' => $data['o_id']))
            ->find();
        if(empty($order)){
            return array('code' => 2, 'msg' => '没有改订单', 'data' => array());
        }
        if($order['o_status']==0){
            $type=1;
        }else if($order['o_status']==1){
            $type=2;
        }
        if($order['o_status']==1 && $order['o_pay_type']==3){
            $end_time=date('Y-m-d H:i:s',time()+60*20);
            $last_time=60*20;
            $pay_price=$order['o_real_price'];
            return array('code' => 1, 'msg' => '订单支付', 'data' => array('end_time'=>$end_time,'last_time'=>$last_time,'pay_price'=>$pay_price,'type'=>$type,'pay_type'=>$order['o_pay_type']));
        }
        if ($order['o_status'] != 0 || $order['o_create_time'] <= time() - 20 * 60) {
            return array('code' => 2, 'msg' => '该订单已不可支付', 'data' => array());
        }
        $end_time=date('Y-m-d H:i:s',$order['o_create_time']+60*20);
        $last_time=$order['o_create_time']+60*20-time();
        if($last_time<0){
            $last_time=0;
        }
        $pay_price=$order['o_real_price'];
        return array('code' => 1, 'msg' => '订单支付', 'data' => array('end_time'=>$end_time,'last_time'=>$last_time,'pay_price'=>$pay_price,'type'=>$type,'pay_type'=>$order['o_pay_type']));
    }
        /**
     * 订单支付
     */
    public function order_pay($header, $data, $user)
    {
        //以下为异步回调订单编号处理
//        $order_num='201907311358453576_7_15165416515';
//        $a=explode('_',$order_num);
//        foreach($a as $v){
//            $len=strlen($v)+1;
//            $times=$v;
//        }
//        $order_num1=substr($order_num,0,-$len);
//        echo $order_num1.'<br/>';
//        echo $times;
//        die;
        //以上为异步回调订单编号处理
        $check = check_array($data, array('o_id','pay_type'));
//        o_id:订单id；
//        pay_type:支付方式：1：微信；2：支付宝；3：货到付款；

        if ($check['code'] != 1) {
            return $check;
        }
        if ($user['u_certification'] == 2) {
            return array('code' => -5, 'msg' => '正在申请实名认证，请认证后操作', 'data' => array());
        }
        if ($user['u_certification'] != 1) {
            return array('code' => -4, 'msg' => '请先实名认证', 'data' => array());
        }
        $order = db('order')
            ->where(array('u_id' => $user['u_id'], 'o_id' => $data['o_id']))
            ->find();
        if(empty($order)){
            return array('code' => 2, 'msg' => '没有该订单', 'data' => array());
        }
        if ($order['o_status'] != 0 || $order['o_create_time'] <= time() - 20 * 60) {
            return array('code' => 2, 'msg' => '该订单已不可支付', 'data' => array());
        }
        if ($data['pay_type'] != 3) {
            if($order['return']!=''){
                return array('code' => 2, 'msg' => '已选择支付方式，请继续支付', 'data' => array());
            }
            if ($data['pay_type'] == 1) {
                $t_wechat = [
                    'appid' => config('wechat.appid'), // APP APPID
                    'app_id' => config('wechat.app_id'), // APP APPID
                    'mch_id' => config('wechat.mch_id'),
                    'key' => config('wechat.key'),//支付密钥
                    'notify_url' => config('wechat.notify_url').'wechat_order_notify',
                    'cert_client' => config('wechat.cert_client'), // optional，退款等情况时用到
                    'cert_key' => config('wechat.cert_key'),// optional，退款等情况时用到
                ];
                $pay_times=$order['pay_times']+1;
                $t_order = [
                    'out_trade_no' => $order['o_order_num'].'_'.$pay_times,
                    'body' => '支付订单：'.$order['o_order_num'],
                    'total_fee' => 1,
//                    'total_fee' => $order['o_real_price']*100, //单位 分
                    'attach'=> '支付订单：'.$order['o_order_num'],
                    'time_start'=>date('YmdHis'),//交易起始时间
                    'time_expire'=>date('YmdHis',time()+60*20),//交易结束时间
                ];
                $json = Pay::wechat($t_wechat)->app($t_order)->getContent();
                $sign = json_decode($json,true);
                db()->startTrans();
                $res=db("order")
                    ->where(array("o_id" => $data['o_id']))
                    ->update(array("o_status" => 0,'o_pay_type'=>$data['pay_type'],'return'=>$json,'pay_times'=>$pay_times));
                if($res!=false){
                    db()->commit();
                    db('order_log')->insert(array('o_id'=>$data['o_id'],'type'=>1,'uid'=>$user['u_id'],'user_name'=>$user['u_real_name'],'create_time'=>time(),'action'=>'申请订单支付：微信'));
                    return array('code' => 1, 'msg' => '订单支付', 'data' => array('pay_type'=>$data['pay_type'],'data'=>$sign));
                }else{
                    $res=db("order")
                        ->where(array("o_id" => $data['o_id']))
                        ->update(array("o_status" => 0,'o_pay_type'=>$data['pay_type'],'return'=>$json,'pay_times'=>$pay_times));
                    db()->commit();
                    db('order_log')->insert(array('o_id'=>$data['o_id'],'type'=>1,'uid'=>$user['u_id'],'user_name'=>$user['u_real_name'],'create_time'=>time(),'action'=>'申请订单支付：微信'));
                    return array('code' => 1, 'msg' => '订单支付', 'data' => array('pay_type'=>$data['pay_type'],'data'=>$sign));
                }
            } else if ($data['pay_type'] == 2) {
                $t_alipay = [
                    'app_id' => config('ali.app_id'),
                    'notify_url' => config('ali.notify_url').'ali_order_notify',
                    'ali_public_key'   => config('ali.ali_public_key'),
                    'private_key' => config('ali.private_key'),
                    'timestamp'=>date('Y-m-d H:i:s'),//发起请求的时间
                ];
                $pay_times=$order['pay_times']+1;
                $order = [
                    'out_trade_no' => $order['o_order_num'].'_'.$pay_times,
                    'total_amount' => 0.01, //单位元
//                    'total_amount' => $order['o_real_price'], //单位元
                    'subject' => '订单：'.$order['o_order_num'],
//                    'body' =>  $body,//自定义参数
                    'body' =>  '订单：'.$order['o_order_num'],//自定义参数
                    'it_b_pay'=>'20m',//支付过期时间
                ];
                $sign = Pay::alipay($t_alipay)->app($order)->getContent();
                db()->startTrans();
                $res=db("order")
                    ->where(array("o_id" => $data['o_id']))
                    ->update(array("o_status" => 0,'o_pay_type'=>$data['pay_type'],'return'=>$sign,'pay_times'=>$pay_times));
                if($res!=false){
                    db()->commit();
                    db('order_log')->insert(array('o_id'=>$data['o_id'],'type'=>1,'uid'=>$user['u_id'],'user_name'=>$user['u_real_name'],'create_time'=>time(),'action'=>'申请订单支付：支付宝'));
                    return array('code' => 1, 'msg' => '订单支付', 'data' => array('pay_type'=>$data['pay_type'],'data'=>$sign));
                }else{
                    $res=db("order")
                        ->where(array("o_id" => $data['o_id']))
                        ->update(array("o_status" => 0,'o_pay_type'=>$data['pay_type'],'return'=>$sign,'pay_times'=>$pay_times));
                    db()->commit();
                    db('order_log')->insert(array('o_id'=>$data['o_id'],'type'=>1,'uid'=>$user['u_id'],'user_name'=>$user['u_real_name'],'create_time'=>time(),'action'=>'申请订单支付：支付宝'));
                    return array('code' => 1, 'msg' => '订单支付', 'data' => array('pay_type'=>$data['pay_type'],'data'=>$sign));
                }
                //支付信息
            }
        } else {
            db("order")
                ->where(array("o_id" => $data['o_id']))
                ->update(array("o_status" => 1,'o_pay_type'=>3));
            $system=db('system')->find();
            if($order['o_type']==1){
                $type='配送上门';
            }else if($order['o_type']==2){
                $type='我要自提';
            }
            $url=$system['order_notice'].'你有新的订单，请及时处理:'.date('Y-m-d-H:i:s',$order['o_create_time']).','.$order['o_id'].','.$user['u_store_name'].',货到付款,未支付,'.$type.','.$order['o_real_price'].'';
            $content= file_get_contents($url);
            db('order_log')->insert(array('o_id'=>$data['o_id'],'type'=>1,'uid'=>$user['u_id'],'user_name'=>$user['u_real_name'],'create_time'=>time(),'action'=>'订单支付：货到付款'));
            return array('code' => 1, 'msg' => '购买成功', 'data' => array('pay_type'=>$data['pay_type']));
        }
    }
    /**
     * 继续支付
     */
    public function order_continue_pay($header, $data, $user)
    {
        $check = check_array($data, array('o_id'));
//        o_id:订单id；
        if ($check['code'] != 1) {
            return $check;
        }
        if ($user['u_certification'] == 2) {
            return array('code' => -5, 'msg' => '正在申请实名认证，请认证后操作', 'data' => array());
        }
        if ($user['u_certification'] != 1) {
            return array('code' => -4, 'msg' => '请先实名认证', 'data' => array());
        }
        $order = db('order')
            ->where(array('u_id' => $user['u_id'], 'o_id' => $data['o_id']))
            ->find();
        if ($order['o_pay_type'] != 3) {
            if ($order['o_status'] != 0 || $order['o_create_time'] <= time() - 20 * 60) {
                return array('code' => 2, 'msg' => '该订单已不可支付', 'data' => array());
            }
            if ($order['o_pay_type'] == 1) {
                $json = $order['return'];
                $sign = json_decode($json,true);
                db('order_log')->insert(array('o_id'=>$data['o_id'],'type'=>1,'uid'=>$user['u_id'],'user_name'=>$user['u_real_name'],'create_time'=>time(),'action'=>'继续支付订单：微信'));
                return array('code' => 1, 'msg' => '订单支付', 'data' => array('pay_type'=>$order['o_pay_type'],'data'=>$sign));
                //支付信息
            } else if ($order['o_pay_type'] == 2) {
                $sign = $order['return'];
                db('order_log')->insert(array('o_id'=>$data['o_id'],'type'=>1,'uid'=>$user['u_id'],'user_name'=>$user['u_real_name'],'create_time'=>time(),'action'=>'继续支付订单：支付宝'));
                return array('code' => 1, 'msg' => '订单支付', 'data' => array('pay_type'=>$order['o_pay_type'],'data'=>$sign));
                //支付信息
            }
        } else {
            if ($order['o_pay_status'] != 0) {
                return array('code' => 2, 'msg' => '该订单已支付', 'data' => array());
            }
            if (empty($data['pay_type'])) {
                return array('code' => 2, 'msg' => '请传入支付方式', 'data' => array());
            }
            if ($data['pay_type'] == 1) {
                $t_wechat = [
                    'appid' => config('wechat.appid'), // APP APPID
                    'app_id' => config('wechat.app_id'), // APP APPID
                    'mch_id' => config('wechat.mch_id'),
                    'key' => config('wechat.key'),//支付密钥
                    'notify_url' => config('wechat.notify_url').'wechat_order_notify',
                    'cert_client' => config('wechat.cert_client'), // optional，退款等情况时用到
                    'cert_key' => config('wechat.cert_key'),// optional，退款等情况时用到
                ];
                $pay_times=$order['pay_times']+1;
                $t_order = [
                    'out_trade_no' => $order['o_order_num'].'_'.$pay_times,
                    'body' => '支付订单：'.$order['o_order_num'],
                    'total_fee' => 1,
//                    'total_fee' => $order['o_real_price']*100, //单位 分
                    'attach'=> '支付订单：'.$order['o_order_num'],
                    'time_start'=>date('YmdHis'),//交易起始时间
                    'time_expire'=>date('YmdHis',time()+60*20),//交易结束时间
                ];
                $json = Pay::wechat($t_wechat)->app($t_order)->getContent();
                $sign = json_decode($json,true);
                db()->startTrans();
                $res=db("order")
                    ->where(array("o_id" => $data['o_id']))
                    ->update(array('return'=>$json,'pay_times'=>$pay_times));
                if($res!=false){
                    db()->commit();
                    db('order_log')->insert(array('o_id'=>$data['o_id'],'type'=>1,'uid'=>$user['u_id'],'user_name'=>$user['u_real_name'],'create_time'=>time(),'action'=>'货到付款继续支付订单：微信'));
                    return array('code' => 1, 'msg' => '订单支付', 'data' => array('pay_type'=>$data['pay_type'],'data'=>$sign));
                }else{
                    $res=db("order")
                        ->where(array("o_id" => $data['o_id']))
                        ->update(array('return'=>$json,'pay_times'=>$pay_times));
                    db()->commit();
                    db('order_log')->insert(array('o_id'=>$data['o_id'],'type'=>1,'uid'=>$user['u_id'],'user_name'=>$user['u_real_name'],'create_time'=>time(),'action'=>'货到付款继续支付订单：微信'));
                    return array('code' => 1, 'msg' => '订单支付', 'data' => array('pay_type'=>$data['pay_type'],'data'=>$sign));
                }
                //支付信息
            } else if ($data['pay_type'] == 2) {
                //支付宝支付
                $t_alipay = [
                    'app_id' => config('ali.app_id'),
                    'notify_url' => config('ali.notify_url').'ali_order_notify',
                    'ali_public_key'   => config('ali.ali_public_key'),
                    'private_key' => config('ali.private_key'),
                ];
                $pay_times=$order['pay_times']+1;
                $order = [
                    'out_trade_no' => $order['o_order_num'].'_'.$pay_times,
                    'total_amount' => 0.01, //单位元
//                    'total_amount' => $order['o_real_price'], //单位元
                    'subject' => '订单：'.$order['o_order_num'],
//                    'body' =>  $body,//自定义参数
                    'body' =>  '订单：'.$order['o_order_num'],//自定义参数
                    'it_b_pay'=>'20m',//支付过期时间
                ];
                $sign = Pay::alipay($t_alipay)->app($order)->getContent();
                db()->startTrans();
                $res=db("order")
                    ->where(array("o_id" => $data['o_id']))
                    ->update(array('return'=>$sign,'pay_times'=>$pay_times));
                if($res!=false){
                    db()->commit();
                    db('order_log')->insert(array('o_id'=>$data['o_id'],'type'=>1,'uid'=>$user['u_id'],'user_name'=>$user['u_real_name'],'create_time'=>time(),'action'=>'货到付款继续支付订单：支付宝'));
                    return array('code' => 1, 'msg' => '订单支付', 'data' => array('pay_type'=>$data['pay_type'],'data'=>$sign));
                }else{
                    $res=db("order")
                        ->where(array("o_id" => $data['o_id']))
                        ->update(array('return'=>$sign,'pay_times'=>$pay_times));
                    db()->commit();
                    db('order_log')->insert(array('o_id'=>$data['o_id'],'type'=>1,'uid'=>$user['u_id'],'user_name'=>$user['u_real_name'],'create_time'=>time(),'action'=>'货到付款继续支付订单：支付宝'));
                    return array('code' => 1, 'msg' => '订单支付', 'data' => array('pay_type'=>$data['pay_type'],'data'=>$sign));
                }
                //支付信息
            }else{
                return array('code' => 2, 'msg' => '请选择支付方式', 'data' => array());
            }
            return array('code' => 1, 'msg' => '继续支付', 'data' => $data0);
        }
    }
    /**
     * 收货
     */
    public function order_collect($header, $data, $user)
    {
        $check = check_array($data, array('o_id'));
//        o_id:订单id；
        if ($check['code'] != 1) {
            return $check;
        }
        $order = db('order')
            ->where(array('u_id' => $user['u_id'], 'o_id' => $data['o_id']))
            ->find();
        if($order['o_status']!=1){
            return array('code' => 2, 'msg' => '该订单不可收货', 'data' => array());
        }
        if($order['o_pay_type']==3 && $order['o_pay_status']==0){
            return array('code' => 2, 'msg' => '请先支付', 'data' => array());
        }
        /*
        //以下判断是否到提货、收货时间
        $time=explode(' ',$order['o_delivery_time']);
        $day=$time[0];
        $time1=explode('-',$time[1]);
        $min_time=strtotime($day.' '.$time1[0]);
        if($min_time>time()){
            if($order['o_type']==1){
                return array('code' => 2, 'msg' => '还未到设置的配送时间', 'data' => array());
            }else if($order['o_type']==2){
                return array('code' => 2, 'msg' => '还未到设置的提货时间', 'data' => array());
            }
        }
        //以上判断是否到提货、收货时间
        */
        $res=db('order')
            ->where(array('u_id' => $user['u_id'], 'o_id' => $data['o_id']))
            ->update(array('o_end_time'=>time(),'o_status'=>10));
        if($res!==false){
            $this->give_integral($order,$user);
            db('order_log')->insert(array('o_id'=>$data['o_id'],'type'=>1,'uid'=>$user['u_id'],'user_name'=>$user['u_real_name'],'create_time'=>time(),'action'=>'订单收货'));
            return array('code' => 1, 'msg' => '收货成功', 'data' => array());
        }else{
            return array('code' => 2, 'msg' => '收货失败', 'data' => array());
        }
    }
    /**
     * 赠送积分
     */
    public function give_integral($order,$user)
    {
        $old_integral=$user['u_integral'];
        $integral=$order['o_add_integral'];
        $status=1;
        $new_integral= $old_integral+$integral;
        $res1=db('user a')
            ->where(array('u_id'=>$user['u_id'],'u_status'=>1))
            ->update(array('u_integral'=>$new_integral));
        $data1=array('u_id'=>$user['u_id'],'o_id'=>$order['o_id'],'o_order_num'=>$order['o_order_num'],'old_integral'=>$old_integral,'new_integral'=>$new_integral,'ui_integral'=>$integral,'ui_status'=>$status,'ui_type'=>1,'ui_create_time'=>time());
        $res2=db('user_integral')->insertGetId($data1);

    }
    /**
     * 申请退货
     */
    public function order_return($header, $data, $user)
    {
        $check = check_array($data, array('o_id','reason'));
//        o_id:订单id；
        if ($check['code'] != 1) {
            return $check;
        }
        if($data['reason']==''){
            return array('code' => 2, 'msg' => '请输入退货原因', 'data' => array());
        }
        $order = db('order')
            ->where(array('u_id' => $user['u_id'], 'o_id' => $data['o_id']))
            ->find();
        if($order['o_status']!=10){
            return array('code' => 2, 'msg' => '该订单不可退货', 'data' => array());
        }
        $return = db('order_return')
            ->where(array("o_id" => $data['o_id']))
            ->order("or_id desc")
            ->find();
        if(!empty($return)){
            return array('code' => 2, 'msg' => '该订单已申请过一次退货了，不可再次退货', 'data' => array());
        }
        $data1=array('o_id'=>$order['o_id'],'or_reason'=>$data['reason'],'or_create_time'=>time(),'or_status'=>1);
        db()->startTrans();
        $res1=db('order_return')
            ->insertGetId($data1);
        $res2=db('order')
            ->where(array('u_id' => $user['u_id'], 'o_id' => $data['o_id']))
            ->update(array('o_status'=>9));
        if($res1>0 && $res2!==false){
            db()->commit();
            db('order_log')->insert(array('o_id'=>$data['o_id'],'type'=>1,'uid'=>$user['u_id'],'user_name'=>$user['u_real_name'],'create_time'=>time(),'action'=>'申请退货，原因：'.$data['reason']));
            return array('code' => 1, 'msg' => '退货申请成功', 'data' => array());
        }else{
            db()->rollback();
            return array('code' => 0, 'msg' => '退货申请失败', 'data' => array());
        }
    }
    /**
     * 申请退货
     */
    public function order_status($header, $data, $user)
    {
        $check = check_array($data, array('o_id'));
//        o_id:订单id；
        if ($check['code'] != 1) {
            return $check;
        }
        $order = db('order')
            ->where(array('u_id' => $user['u_id'], 'o_id' => $data['o_id']))
            ->find();
        if(empty($order)){
            return array('code' => 2, 'msg' => '没有该订单', 'data' => array());
        }
        return array('code' => 1, 'msg' => '订单状态', 'data' => array('pay_status'=>$order['o_pay_status']));
    }
}